package joinpay

import (
	"bytes"
	"encoding/json"
	"fmt"
	"hotgo/utility/joinpay/utils"
	"strconv"
	"strings"
)

const AccountBalanceApi = "https://www.joinpay.com/payment/pay/accountBalanceQuery" // 可取余额查询

type AccountBalanceReq struct {
	UserNo string `json:"userNo"` // 商户编号
	Hmac   string `json:"hmac"`   // 签名数据
}

type AccountBalanceResp struct {
	Data struct {
		UserNo                    string  `json:"userNo"`
		UserName                  string  `json:"userName"`
		Currency                  int     `json:"currency"`
		UseAbleSettAmount         float64 `json:"useAbleSettAmount"`
		AvailableSettAmountFrozen float64 `json:"availableSettAmountFrozen"`
		ErrorCode                 string  `json:"errorCode"`
		ErrorDesc                 string  `json:"errorDesc"`
		Hmac                      string  `json:"hmac"`
	} `json:"data"`
	StatusCode int    `json:"statusCode"`
	Message    string `json:"message"`
}

// AccountBalanceQuery 可取余额查询
func AccountBalanceQuery(merchantKey string, req AccountBalanceReq) (*AccountBalanceResp, error) {
	signByMD5 := utils.SignByMD5(req.UserNo, merchantKey)
	req.Hmac = signByMD5
	marshal, err := json.Marshal(req)
	if err != nil {
		return nil, err
	}
	body, err := utils.PostRequest(AccountBalanceApi, marshal)
	if err != nil {
		return nil, err
	}
	var resp *AccountBalanceResp
	err = json.Unmarshal(body, &resp)
	// 验签
	var respData bytes.Buffer
	respData.WriteString(strconv.Itoa(resp.StatusCode))
	respData.WriteString(resp.Message)
	respData.WriteString(resp.Data.UserNo)
	respData.WriteString(resp.Data.UserName)
	respData.WriteString(strconv.Itoa(resp.Data.Currency))
	respData.WriteString(fmt.Sprintf("%.2f", resp.Data.UseAbleSettAmount))
	respData.WriteString(fmt.Sprintf("%.2f", resp.Data.AvailableSettAmountFrozen))
	respData.WriteString(resp.Data.ErrorCode)
	respData.WriteString(resp.Data.ErrorDesc)
	signResp := utils.SignByMD5(respData.String(), merchantKey)
	//logx.Infof("响应结果拼接 --------------------------------->%s", respData.String())
	//logx.Infof("响应结果拼接签名 --------------------------------->%s", signResp)
	//logx.Infof("响应结果拼接签名 --------------------------------->%s", resp.Data.Hmac)
	if signResp != strings.ToUpper(resp.Data.Hmac) {
		//logx.Info("响应结果验签 --------------------------------->不符合")
		return resp, err
	}
	return resp, err
}
